package service

import (
	"database/sql"
	"errors"
	"ssr/common"
	"ssr/dto"
	"ssr/models"

	"gorm.io/gorm"
)

type AuthService struct {
	db *gorm.DB
}

func NewAuthService() *AuthService {
	return &AuthService{
		db: common.GetDB(),
	}
}

type UserLogin struct {
	Id        string         `json:"id"`
	Username  string         `json:"username"`
	Password  string         `json:"password"`
	Email     sql.NullString `json:"email" gorm:""`
	Phone     sql.NullString `json:"phone"`
	Status    int            `json:"status"`
	CreatedAt string         `json:"createdAt"`
}

func (s *AuthService) Login(loginParams dto.JackpotUserLoginDTO) (map[string]interface{}, error) {
	var user models.GameUser
	if err := s.db.Where("username = ?", loginParams.Username).First(&user).Error; err != nil {
		return nil, err
	}
	if user.Password != loginParams.Password {
		return nil, errors.New("密码错误")
	}
	if user.State != 1 {
		return nil, errors.New("账号未激活")
	}
	token, err := common.GenerateToken(user.ID, user.Username)
	if err != nil {
		return nil, err
	}
	return map[string]interface{}{
		"token": token,
	}, nil
}
